//封装grid基本参数
$.extend($.fn.datagrid.defaults, {
	//url:_ctx+'/admin/user/list',
	//columns:[],
	fitColumns:true,
	border:false,
	fit:true,
	//toolbar:[],
	striped:true,
	onAddToolbar:function(){},
	onBeforeLoad:function(){
		//$(this).prepend('<div class="datagrid-toolbar"><table cellspacing="0" cellpadding="0"><tbody><tr><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">新增</span><span class="l-btn-icon icon icon-add">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">修改</span><span class="l-btn-icon icon icon-edit">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">授权</span><span class="l-btn-icon icon icon-auth">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">删除</span><span class="l-btn-icon icon icon-delete">&nbsp;</span></span></a></td></tr></tbody></table></div>');
	},
	onBeforeOpen:function(){	
		//console.log(this);
		//$(this).prepend('<div class="datagrid-toolbar"><table cellspacing="0" cellpadding="0"><tbody><tr><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">新增</span><span class="l-btn-icon icon icon-add">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">修改</span><span class="l-btn-icon icon icon-edit">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">授权</span><span class="l-btn-icon icon icon-auth">&nbsp;</span></span></a></td><td><div class="datagrid-btn-separator"></div></td><td><a href="javascript:void(0)" class="l-btn l-btn-small l-btn-plain" group="" id=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">删除</span><span class="l-btn-icon icon icon-delete">&nbsp;</span></span></a></td></tr></tbody></table></div>');
	},
	//idField
	loadMsg:'加载中...',
	pagination:true,
	rownumbers:true,
	pageNumber:1,
	pageSize:20,
	pageList:[10,20,30,40,50,100],
	singleSelect:false,
	ctrlSelect:true,
	queryParams:{},
	sortName:null,
	sortOrder:'asc',
	multiSort:false,
	remoteSort:true,
	onOpen:function(){
		//添加权限按钮
		var toolbars = $(this).find("table.datagrid-f").eq(0).datagrid('options').appToolbar;
		if(toolbars){
			var tb=$("<div class=\"datagrid-header\" style=\"height:26px;padding:2px;\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(this);
			var tr=tb.find("tr");
			for(var i=0;i<toolbars.length;i++){
				var btn=toolbars[i];
				if(btn=="-"){
					$("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr);
				}else{
					if(!btn.key||isAuth(btn.key)){
						var td=$("<td></td>").appendTo(tr);
						var _65=$("<a href=\"javascript:;\"></a>").appendTo(td);
						_65[0].onclick=eval(btn.handler||function(){});
						_65.linkbutton($.extend({},btn,{plain:true}));
					}
				}
				
			}
		}
		
		var forms = $(this).parents("div.easyui-layout").find("form");
		if(forms.size()>0){
			var queryForm = forms.eq(0);
			queryForm.get(0).grid = $(this).find("table.datagrid-f").eq(0).get(0);
			queryForm.on("submit",function(){
				var params = form2json(this);
				$(this.grid).datagrid("load",params);
				return false;
			});
		}
	}
}); 

//封装grid基本参数
$.extend($.fn.treegrid.defaults, {
	//url:_ctx+'/admin/user/list',
	//columns:[],
	selectChildOnParent:true, //选择子孩子节点时自动选择父节点
	idField:'id',
	treeField:'name',
	fitColumns:true,
	fit:true,
	lines:true,
	pagination:false,
	border:false,
	checkOnSelect:true,
	selectOnCheck:true,
	//toolbar:[],
	striped:true,
	//idField
	loadMsg:'加载中...',
	rownumbers:false,
	pageNumber:1,
	pageSize:20,
	pageList:[10,20,30,40,50,100],
	singleSelect:false,
	ctrlSelect:true,
	queryParams:{},
	onOpen:function(){
		//添加权限按钮
		var toolbars = $(this).find("table.datagrid-f").eq(0).treegrid('options').appToolbar;
		if(toolbars){
			var tb=$("<div class=\"datagrid-header\" style=\"height:26px;padding:2px;\"><table cellspacing=\"0\" cellpadding=\"0\"><tr></tr></table></div>").prependTo(this);
			var tr=tb.find("tr");
			for(var i=0;i<toolbars.length;i++){
				var btn=toolbars[i];
				if(btn=="-"){
					$("<td><div class=\"datagrid-btn-separator\"></div></td>").appendTo(tr);
				}else{
					if(!btn.key||isAuth(btn.key)){
						var td=$("<td></td>").appendTo(tr);
						var _65=$("<a href=\"javascript:;\"></a>").appendTo(td);
						_65[0].onclick=eval(btn.handler||function(){});
						_65.linkbutton($.extend({},btn,{plain:true}));
					}
				}
				
			}
		}
		
		var forms = $(this).parents("div.easyui-layout").find("form");
		if(forms.size()>0){
			var queryForm = forms.eq(0);
			queryForm.get(0).grid = $(this).find("table.datagrid-f").eq(0).get(0);
			queryForm.on("submit",function(){
				var params = form2json(this);
				$(this.grid).treegrid("load",params);
				return false;
			});
		}
	},
	onSelect:function(row){
		if($(this).treegrid('options').selectChildOnParent){
			if($(this).treegrid('options').columns[0][0].checkbox){
				var selectedParentFun = function(tree,node){
					var parent = $(tree).treegrid('getParent',node.id);
					if(parent){
						$(tree).treegrid('select',parent.id);
						selectedParentFun(tree,parent);
					}
				}
				selectedParentFun(this,row);
			}
		}
	},
	onUnselect:function(row){
		if($(this).treegrid('options').selectChildOnParent){
			if($(this).treegrid('options').columns[0][0].checkbox){
				if(row.state=='open'){
					var cc = $(this).treegrid('getChildren',row.id);
					for(var i=0;i<cc.length;i++){
						$(this).treegrid('unselect',cc[i].id);
					}
				}
			}
		}
	}
});

//封装表单处理
$.extend($.fn.form.defaults, {
	onSubmit: function(){
		var isValid = $(this).form('validate');
		if (isValid){
			$.messager.progress();
		}
		return isValid;
	},
	success:function(jsonStr){
		$.messager.progress('close');
		var json = str2Json(jsonStr);
		if(json.success){
			if(this.dialog){
				var opts = $(this.dialog).dialog('options');
				if(opts.allowClose){
					$(this.dialog).dialog("close");
				}
			}
			if(this.grid){
				var $grid = $(this.grid);
				if($grid.attr('isTree')=='true'){
					$grid.treegrid("reload");
				}else{
					$grid.datagrid("reload");
				}
			}
		}
		if(json.msg){
			$.appTip(json.msg);
		}
	}
}); 
		
$.extend($.fn.dialog.defaults, {
	title: '对话框',
	width: 700,
	allowClose:true,//--------------- 允许自动关闭对话框
	//height: 400,
	closed: false,
	cache: false,
	resizable:false,
	minimizable:false,
	maximizable:false,
	collapsible:true,
	maximized:false,
	//href: _tpl+'/admin/user_add.tpl.php', //url方式
	//content:"dsafsd", //html方式
	modal: true,
	onClose : function() {
        $(this).dialog('destroy');
    },
	onLoad:function(){
		//自动封装dialog 的form 和关闭后的grid
		var opts = $(this).dialog("options");
		if($(this).find("form").size()>0){
			var form  = $(this).find("form").eq(0);
			var url = null;
			var formOpts = {
				url:null,
				dialog:this,
				grid:opts.grid||null
			}
			if(opts.form){
				formOpts = $.extend(formOpts, opts.form);
			}
			this.form = form.form(formOpts);
			if(opts.data){
				this.form.form("load",opts.data);
			}
		}
		
		//加载数据
		var remoteData = $(this).dialog("options").remoteData;
		if(remoteData&&remoteData.url){
			$.appAjax({
				url:remoteData.url,
				dialog:this,
				showProgress:true,
				success:remoteData.success||function(datas){
					if(this.showProgress){
						$.messager.progress('close');
					}
					$(this.dialog).find("form").eq(0).form('load',datas);
				}
			});
		}
	},
	onOpen:function(){
		//垂直居中显示
		//$(this).panel("move",{top:$(document).scrollTop() + ($(window).height()-250) * 0.5});
		//顶部显示
		$(this).panel("move",{top:0});
		
	},
	//扩展的字段data：
	data:{}, //{} form自动加载数据$(this).form('load',loadData);	
	dataUrl:null,//远程加载数据的Url
	form:{	//可按easyui标准定义

	},
	grid:null//grid的dom对象
	/*
	buttons : [ {
		text : 'OK',
		iconCls : 'icon-ok',
		handler : function() {
			//提交表单
		}
	}, {
		text : 'CANCEL',
		iconCls : 'icon-cancel',
		handler : function() {
			$("#dd").dialog('close');
		}
	}]
	*/
}); 

$.extend($.fn.datalist.defaults, {
	method: 'get',
	valueField:'id',
	textField:'name',
	loadMsg:'加载数据...',
	fit:true,
	fitColumns:true,
	checkOnSelect:true,
	selectOnCheck:true,
	lines:true,
	checkbox: true,
	singleSelect:false
	//,onBeforeSelect: function(){return false;}开启选择无效
}); 
 
/**
 * 针对panel window dialog三个组件拖动时会超出父级元素的修正
 * 如果父级元素的overflow属性为hidden，则修复上下左右个方向
 * 如果父级元素的overflow属性为非hidden，则只修复上左两个方向
 * @param left
 * @param top
 * @returns
 */
var easyuiPanelOnMove = function(left, top){
	if ($(this).panel('options').reSizing) 
		return;
	var parentObj = $(this).panel('panel').parent();
	var width = $(this).panel('options').width;
	var height = $(this).panel('options').height;
	var right = left + width;
	var buttom = top + height;
	var parentWidth = parentObj.width();
	var parentHeight = parentObj.height();
	
	if (left < 0) {
		$(this).panel('move', {
			left: 0
		});
	}
	if (top < 0) {
		$(this).panel('move', {
			top: 0
		});
	}
	
	if (parentObj.css("overflow") == "hidden") {
		var inline = $.data(this, "window").options.inline;
		if(inline==false){
			parentObj = $(window);
		}
		if (left > parentObj.width() - width) {
			$(this).panel('move', {
				"left": parentObj.width() - width
			});
		}
		if (top > parentObj.height() - height) {
			$(this).panel('move', {
				"top": parentObj.height() - height
			});
		}
	}
};
$.fn.window.defaults.onMove = easyuiPanelOnMove;
$.fn.panel.defaults.onMove = easyuiPanelOnMove;
$.fn.dialog.defaults.onMove = easyuiPanelOnMove;

$.appTip = function($msg){
	$.messager.show({
		title:'操作提示',
		msg:$msg,
		showType:'show',
		//右上角上自动弹出
		style:{
				left:'',
				right:0,
				top:document.body.scrollTop+document.documentElement.scrollTop,
				bottom:''
		}
	});
	
}

$.appAlert = function($msg){
	$.messager.alert('操作提示',$msg);
}

$.appConfirm = function($msg,$callFun){
	$.messager.confirm('操作提示', $msg, $callFun);
}

/**
 *封装ajax方法
 *$opts,为$.ajax 通用参数，以下为$opts扩展
 *$opts.grid 对应datagrid的dom对象，ajax调用后会自动刷新当前datagrid
 *$opts.showProgress = true , 调用ajax过程中自动出现遮罩进度条
 */
$.appAjax = function($opts){
	var defaults = {
		//url:null,
		//data:null,
		type:'post',
		dataType:'json',
		grid:null,
		showProgress:true,
		beforeSend:function(){
			if(this.showProgress){
				$.messager.progress();
			}
		},
		success: function(json){
			if(this.showProgress){
				$.messager.progress('close');
			}
			if(json.success){
				if(this.grid){
					var $grid = $(this.grid);
					if($grid.attr('isTree')=='true'){
						$grid.treegrid("reload");
					}else{
						$grid.datagrid("reload");
					}
				}
			}
			if(json.msg){
				$.appTip(json.msg);
			}
		},
		error:function(data){
			if(this.showProgress){
				$.messager.progress('close');
			}
			$.appTip("系统异常，请重试或联系相关人员！");
		}
	}
	$opts = $.extend(defaults,$opts);
	if($opts.confirmTitle){
		$.appConfirm($opts.confirmTitle,function(r){
			if(r){
				$.ajax($opts);
			}
		});
	}else{
		$.ajax($opts);
	}
}

$.extend($.fn.validatebox.defaults.rules, {
    letter: {
        validator: function(value){
			var reg = /^[a-zA-Z0-9_]+$/;
			return reg.test(value);
        },
        message: '该项由字母、数字、下划线组成.'
    }
});

//动态加载字典
_dic = {};
_dicKeys = [];
$.appLoadDic = function(kinds,async,callback){
	var typs = kinds.split(',');
	var ids = [];
	for(var i=0;i<typs.length;i++){
		if($.inArray(typs[i], _dicKeys)==-1){
			_dicKeys.push(typs[i]);
			ids.push(typs[i]);
		}
	}
	if(ids.length==0) return ;
	$.appAjax({
		url:_ctx+'/config/dynamicDic.php?kind='+ids.join(','),
		async:async||false,
		showProgress:false,
		dataType:'text',
		success: function(text){
			eval('('+text+')');
			if(callback) callback();
		}
	});
}

//字典格式化函数
$.appDicFormat = function(dicKey,value){
	//不在数组中
	if($.inArray(dicKey, _dicKeys)==-1){
		//获取字典
		$.appLoadDic(dicKey);
	}
	var datas = _dic[dicKey];
	var result = "";
	for(var i=0;i<datas.length;i++){
		if(datas[i].value==value.toString()){
			result = datas[i].text;
			break;
		} 
	}
	return result;
}

//字典数据数组
$.appDicDatas = function(dicKey){
	//不在数组中
	if($.inArray(dicKey, _dicKeys)==-1){
		//获取字典
		$.appLoadDic(dicKey);
	}
	return _dic[dicKey];
}

//根据内部dom快速获取grid对象，innerObj为grid的内部对象，如按钮组事件中的this
function getDatagrid(innerDom){
	var grid = $(innerDom).parents('div.datagrid').find('table.datagrid-f').eq(0);
	return grid;
}